package com.example.controller;


import com.example.dto.SysDeptDTO;
import com.example.model.api.Result;
import com.example.service.SysDeptService;
import com.example.validator.AssertUtils;
import com.example.validator.ValidatorUtils;
import com.example.validator.group.AddGroup;
import com.example.validator.group.DefaultGroup;
import com.example.validator.group.UpdateGroup;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.security.access.prepost.PreAuthorize;

import java.util.HashMap;
import java.util.List;

/**
 * 部门管理
 */
@RestController
@RequestMapping("dept")
@Tag(name = "部门管理")
public class SysDeptController {
    @Autowired
    private SysDeptService sysDeptService;

    @GetMapping("list")
    @Operation(summary = "列表")
    @PreAuthorize("hasAuthority('sys:dept:list')")
    public Result<List<SysDeptDTO>> list(){
        List<SysDeptDTO> list = sysDeptService.list(new HashMap<>(1));

        return new Result<List<SysDeptDTO>>().ok(list);
    }

    @GetMapping("{id}")
    @Operation(summary = "信息")
    @PreAuthorize("hasAuthority('sys:dept:info')")
    public Result<SysDeptDTO> get(@PathVariable("id") Long id){
        SysDeptDTO data = sysDeptService.get(id);

        return new Result<SysDeptDTO>().ok(data);
    }

    @PostMapping
    @Operation(summary = "保存")
//    @LogOperation("Save Dept")
    @PreAuthorize("hasAuthority('sys:dept:save')")
    public Result<String> save(@RequestBody SysDeptDTO dto){
        //效验数据
        ValidatorUtils.validateEntity(dto, AddGroup.class, DefaultGroup.class);

        sysDeptService.save(dto);

        return new Result<String>().ok("ok");
    }

    @PutMapping
    @Operation(summary = "修改")
//    @LogOperation("Update Dept")
    @PreAuthorize("hasAuthority('sys:dept:update')")
    public Result<String> update(@RequestBody SysDeptDTO dto){
        //效验数据
        ValidatorUtils.validateEntity(dto, UpdateGroup.class, DefaultGroup.class);

        sysDeptService.update(dto);

        return new Result<String>().ok("ok");
    }

    @DeleteMapping("{id}")
    @Operation(summary = "删除")
//    @LogOperation("Delete Dept")
    @PreAuthorize("hasAuthority('sys:dept:delete')")
    public Result<String> delete(@PathVariable("id") Long id){
        //效验数据
        AssertUtils.isNull(id, "id");

        sysDeptService.delete(id);

        return new Result<String>().ok("ok");
    }
}